var defaultPlaylist = {'name': 'Test', 'id': 'PLE4xflB1hA2QjdWt2ETx557LDEoJyGvfz'};
var defaultPluginAction = {'action': 'DO_NOTHING'};

var pluginActionOptions = [ 
		{'desc':'do nothing', 'value':'DO_NOTHING'}, 
		{'desc':'add to playlist', 'value':'ADD'},  
		{'desc':'download to MP3', 'value':'DOWNLOAD'} ];

var currentPlaylist;
var currentTab;
var pluginAction;

function setDashboard(message) {
	"use strict";
	document.getElementById('dashboard').innerHTML = message;
}

function sharePlaylist() {
	"use strict";
	chrome.tabs.create({
        url: "http://acxxxiom.appspot.com"
    });
}

function openPlaylist() {
	"use strict";
	chrome.tabs.create({
        url: "http://www.youtube.com/playlist?list=" + currentPlaylist.id
    });
}

function changePlaylist() {
	var sharedPlaylists = document.getElementById('sharedPlaylists');	
	currentPlaylist = {'name': sharedPlaylists.options[sharedPlaylists.selectedIndex].text, 
					   'id': sharedPlaylists.options[sharedPlaylists.selectedIndex].value};
    chrome.storage.local.set({'selectedPlaylist': currentPlaylist}, function() {
		setDashboard('Selected playlist changed to ' +				
		currentPlaylist.name);
		
	});
}

function changeDefaultPluginAction() {
	var defaultPluginAction = document.getElementById('defaultPluginAction');	
	pluginAction = {'action' : defaultPluginAction.options[defaultPluginAction.selectedIndex].value};
	chrome.storage.local.set({'pluginAction': pluginAction}, function() {
		setDashboard('Plugin Action changed to ' +				
		pluginAction.action);
		
	});
}

function downloadFileFromText(downloadUrl, filename, watchVideoURLs) {
	setDashboard("Download file " + filename);
    var a = document.createElement('a');
    a.href = downloadUrl;
    a.download = filename;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click(); //this is probably the key - simulating a click on a download link
    delete a;// we don't need this anymore
	
	if (watchVideoURLs.length > 0) {
		//call next...
		downloadURLsAsMP3(watchVideoURLs)
	}
}

function getListenToYoutubeConvertionStatus(statusUrl, watchVideoURLs) {
		
	var xhr = new XMLHttpRequest();
	xhr.open("GET", statusUrl, true);
	xhr.setRequestHeader("Content-type","application/json");
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {    
			console.log(xhr.status + " " + xhr.responseText);	
			
			var xmlDoc = xhr.responseXML;
			var status = xmlDoc.getElementsByTagName("conversioncloud")[0].getElementsByTagName("status")[0];
			//<status step="ticket" percent="0" info="Please wait..."/>
			if (status.getAttribute("step") === "finished") {
				var downloadurl = xmlDoc.getElementsByTagName("conversioncloud")[0].getElementsByTagName("downloadurl")[0].firstChild.data;
				var filename = xmlDoc.getElementsByTagName("conversioncloud")[0].getElementsByTagName("file")[0].firstChild.data;
				downloadFileFromText(downloadurl, filename, watchVideoURLs);
			} else {				
				setDashboard('Processig, step: ' +	status.getAttribute("step") + ', percent ' + status.getAttribute("percent") + ', ' + status.getAttribute("info"));
				//repeat until success
				setTimeout(function () {
					getListenToYoutubeConvertionStatus(statusUrl, watchVideoURLs);
				}, 5000);
			}
		}
	}
	xhr.send();

}

function downloadURLsAsMP3(watchVideoURLs) {
	 var xhr = new XMLHttpRequest();
	 xhr.open("POST", "http://www.listentoyoutube.com/cc/conversioncloud.php", true);
     xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) { 	
			if (xhr.status == 200) {   
				//2 - get status url
				var status = JSON.parse(xhr.responseText.replace("(", "").replace(")", ""));	
				getListenToYoutubeConvertionStatus(status.statusurl, watchVideoURLs);		
			} else {
				setDashboard("Convertion failed with " + xhr.status);
			}
		}
	}
	//1 - start conversion
	xhr.send("mediaurl=" + watchVideoURLs.shift());
}

//download currently played song
function downloadAsMP3() {
    var watchVideoURLs = [currentTab.url];
	
	downloadURLsAsMP3(watchVideoURLs);
}

//download whole playlist
function downloadPlaylist() {

   var xhr = new XMLHttpRequest();
 xhr.open("GET", "http://acxxxiom.appspot.com/getPlaylistItemsVideoId?playlistId=" + currentPlaylist.id, true);
 xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {    	 
	 var videoIds = JSON.parse(xhr.responseText);
	 var watchVideoURLs = [];
	 for (var i in videoIds) {	
		watchVideoURLs.push("https://www.youtube.com/watch?v=" + videoIds[i]);
	 }
	 console.log(watchVideoURLs);
	 downloadURLsAsMP3(watchVideoURLs);
  }
}
 xhr.send();	
}



function addPlaylist(tab) { 
 
 var xhr = new XMLHttpRequest();
 xhr.open("POST", "http://acxxxiom.appspot.com/addPlaylistItem", true);
 xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {    
	 document.getElementById('dashboard').innerHTML = xhr.responseText;
  }
}
 xhr.send("title=" + currentPlaylist.name + "&videoUrl=" + tab.url);
}


function getAllSharedPlaylists() {
 var xhr = new XMLHttpRequest();
 xhr.open("GET", "http://acxxxiom.appspot.com/getSharedPlaylists", true);
 xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {    
	 var allSharedPlaylistsJSON = JSON.parse(xhr.responseText);	 
	 var sharedPlaylists = document.getElementById('sharedPlaylists');
	 for (var i in allSharedPlaylistsJSON) {	 
		var option = document.createElement('option');
		option.setAttribute('value', allSharedPlaylistsJSON[i].id);		
		if (currentPlaylist.name == allSharedPlaylistsJSON[i].name) {
			option.setAttribute('selected', 'selected');
		}
		option.appendChild(document.createTextNode(allSharedPlaylistsJSON[i].name));
		sharedPlaylists.appendChild(option);
	 }
	 
  }
}
 xhr.send();
}

function getPluginActions() {
var defaultPluginActionSelect = document.getElementById('defaultPluginAction');	 
	pluginActionOptions.forEach( function(pluginActionOption) { 
		var option = document.createElement('option');
		option.setAttribute('value', pluginActionOption.value);		
		if (pluginAction == pluginActionOption.value) {
			option.setAttribute('selected', 'selected');
		}
		option.appendChild(document.createTextNode(pluginActionOption.desc));
		defaultPluginActionSelect.appendChild(option);
	});
}

function addWatchedVideoToSelectedPlaylist() {
			
	addPlaylist(currentTab);
	
	setDashboard( 'Adding new video to '+
			currentPlaylist.name +
			'...');		
}

function executePluginAction(action) {
	if ('ADD' == action) {
		addWatchedVideoToSelectedPlaylist();
	} else if ('DOWNLOAD' == action) {
		downloadAsMP3();
	} else {
		setDashboard( 'Do nothing');		
	}

}


function onLoad() {
//add actions to link buttons
 document.getElementById('addWatchedVideo').addEventListener('click', addWatchedVideoToSelectedPlaylist);   
 document.getElementById('shareLink').addEventListener('click', sharePlaylist);  
 document.getElementById('openLink').addEventListener('click', openPlaylist);  
 document.getElementById('downloadLink').addEventListener('click', downloadAsMP3);  
 document.getElementById('downloadPlaylist').addEventListener('click', downloadPlaylist);  
 
 document.getElementById('sharedPlaylists').addEventListener('change', changePlaylist);  
 document.getElementById('defaultPluginAction').addEventListener('change', changeDefaultPluginAction);  


//get selected playlist and mark it 
  chrome.storage.local.get('selectedPlaylist', function(value) {
	 if (!value.selectedPlaylist) {
		console.log('Default playlist.');
		currentPlaylist = defaultPlaylist;
	 } else {		
		currentPlaylist = value.selectedPlaylist;
		console.log('Selected playlist from storage.' + currentPlaylist.name);
	 }	 
	  //populate shared playlist
	 getAllSharedPlaylists();
});
 
 //set current tab
 chrome.windows.getCurrent(
	  function(win) { 
		chrome.tabs.query({'windowId': win.id, 'active': true},
		function(tabArray) {	  	  
		  currentTab = tabArray[0]; }
		)
		
		  //get plugin action, mark it			
		  chrome.storage.local.get('pluginAction', function(value) {
			 if (!value.pluginAction) {
				console.log('Default plugin action.');
				pluginAction = defaultPluginAction;
			 } else {		
				pluginAction = value.pluginAction.action;
				console.log('Selected plugin action from storage.' + pluginAction);
			 }
			 getPluginActions();
			 executePluginAction(value.pluginAction.action);
		});

});	
 
}

//start
window.onload = onLoad();

